package com.elock.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.elock.base.core.Filter;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.Sequence;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.entity.Setting;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.JsonUtils;
import com.elock.base.core.util.SettingUtils;
import com.elock.base.core.util.WebUtils;
import com.elock.entity.Member;
import com.elock.entity.MemberSaleOrg;
import com.elock.entity.PcUserRole;
import com.elock.service.MemberSaleOrgBaseService;
import com.elock.service.MemberService;
import com.elock.service.PcRoleBaseService;
import com.elock.service.PcUserRoleBaseService;
import com.elock.service.SaleOrgBaseService;
import com.elock.service.TerminalMemberService;

/**
 * 用户
 * @author 仁德
 */
@Controller("memberController")
@RequestMapping("/member")
public class MemberController extends BaseController {

	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
	@Resource(name = "pcUserRoleBaseServiceImpl")
	private PcUserRoleBaseService pcUserRoleBaseService;
	@Resource(name = "pcRoleBaseServiceImpl")
	private PcRoleBaseService pcRoleBaseService;
	@Resource(name = "memberSaleOrgBaseServiceImpl")
	private MemberSaleOrgBaseService memberSaleOrgBaseService;
	@Resource(name = "terminalMemberServiceImpl")
	private TerminalMemberService terminalMemberService;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Integer isEdit, Integer memberType, Pageable pageable,
			ModelMap model) {

		List<Filter> fis = new ArrayList<Filter>();
		fis.add(Filter.eq("isEnabled", true));
		model.addAttribute("isEdit", isEdit);
		model.addAttribute("memberType", memberType);
		return "/member/list";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(Integer isEdit, Integer memberType, Pageable pageable,
			ModelMap model) {

		model.addAttribute("isEdit", isEdit);
		model.addAttribute("memberType", memberType);
		return "/member/list_tb";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg list_data(String username, String mobile, String name,
			String pinCode, Long saleOrgId, String startTime, String endTime,
			Integer memberType, Pageable pageable, ModelMap model) {
//		List<Filter> filters = new ArrayList<Filter>();
//		filters.add(Filter.eq("username", username));
//		filters.add(Filter.eq("mobile", mobile));
//		filters.add(Filter.eq("name", name));
//		if (StringUtils.isNotEmpty(startTime)) {
//			filters.add(Filter.ge("createDate",
//					DateUtil.convert(startTime + " 00:00:00")));
//		}
//		if (StringUtils.isNotEmpty(endTime)) {
//			filters.add(
//					Filter.lt("createDate",
//							DateUtils.addDays(
//									DateUtil.convert(endTime + " 00:00:00"),
//									1)));
//		}
//		Page<Member> page = memberService.findPage(filters, null, pageable);

		Page<Map<String, Object>> page = memberService.findPage(username,
				mobile,
				name,
				pinCode,
				saleOrgId,
				startTime,
				endTime,
				memberType,
				pageable);

		String jsonPage = JsonUtils.toJson(page);

		return success(jsonPage);
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Integer memberType, ModelMap model) {

		List<Map<String, Object>> roles = pcRoleBaseService
				.findPage(null, null, null, null, new Pageable()).getContent();
		model.addAttribute("roles", roles);

//		List<PcRole> roles = pcRoleBaseService.findAll();
//		model.addAttribute("roles", roles);

		model.addAttribute("memberType", memberType);
		model.addAttribute("isAdmin", WebUtils.isAdmin());
		model.addAttribute("saleOrg", saleOrgBaseService.getCurrentSaleOrg());

		return "/member/add";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public @ResponseBody ResultMsg save(Member member, Long pc_id, Long parentId,
			Long[] roleId, Long saleOrgId, Boolean isAdministrator, Long[] terminalId,
			HttpServletRequest request, ModelMap model) {

		if (member.getMemberType() == 1) {
			String str = Sequence.getInstance().getSequence("");
			member.setUsername(str);
			member.setMobile(str);
			member.setPassword("888888");
			if (member.getPinCode() != null) {
				Member m = memberService.findByPinCode(member.getPinCode());
				if (m != null) {
					return error("操作员PIN码在系统中已存在");
				}
			}
		}
		else {
			if (ConvertUtil.isEmpty(member.getUsername())
					|| ConvertUtil.isEmpty(member.getPassword())
					|| ConvertUtil.isEmpty(member.getMobile())) {
				// 用户名、密码或手机号未填
				return error("1601001");
			}
			if (member.getUsername().indexOf("admin") != -1) {
				// 非法的用户名
				return error("1601011");
			}
			Setting setting = SettingUtils.get();
			if (member.getUsername().length() < setting.getUsernameMinLength()
					|| member.getUsername().length() > setting.getUsernameMaxLength()) {
				// 用户名长度范围有误
				return error("1601004");
			}
			if (member.getPassword().length() < setting.getPasswordMinLength()
					|| member.getPassword().length() > setting.getPasswordMaxLength()) {
				// 密码长度范围有误
				return error("1601005");
			}
		}
		Member m = memberService.findByMobile(member.getMobile(),
				WebUtils.getCurrentCompanyInfoId());
		if (m != null) {
			// 手机号已存在
			return error("1601006");
		}

		// 保存用户
		long storeMemberId = memberService.saveMember(member,
				roleId,
				saleOrgId,
				isAdministrator,
				terminalId);

		return success().addObjX(storeMemberId);
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, Integer flag, Integer isEdit, Integer memberType,
			ModelMap model) {

		model.addAttribute("isEdit", isEdit);
		Member member = memberService.find(id);
		model.addAttribute("member", member);

//		PcRole arole = pcRoleBaseService.findAdministrator();
//		List<Filter> fis = new ArrayList<Filter>();
//		fis.add(Filter.eq("pcRole", arole));
//		fis.add(Filter.eq("member", member));
//		PcUserRole pcUserRole = pcUserRoleBaseService.find(fis);
		model.addAttribute("isAdministrator", false);
		model.addAttribute("isAdmin", WebUtils.isAdmin());

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("member", member));
		MemberSaleOrg memberSaleOrg = memberSaleOrgBaseService.find(filters);
		if (memberSaleOrg != null) {
			model.addAttribute("saleOrg", memberSaleOrg.getSaleOrg());
		}

		filters.clear();
		filters.add(Filter.eq("member", member));
		List<PcUserRole> userRoles = pcUserRoleBaseService.findList(null, filters, null);
		List<Long> uRoleIds = new ArrayList<Long>();
		for (PcUserRole userRole : userRoles) {
			uRoleIds.add(userRole.getPcRole().getId());
		}
		model.addAttribute("uRoleIds", uRoleIds);

		model.addAttribute("memberType", memberType);

		List<Map<String, Object>> roles = pcRoleBaseService
				.findPage(null, null, null, null, new Pageable()).getContent();
		model.addAttribute("roles", roles);

		List<Map<String, Object>> terminals = memberService.getDaoCenter()
				.getNativeDao()
				.findListMap(
						"select b.* from terminal_member a, terminal b where a.terminal_id=b.id and a.member_id=?",
						new Object[] { id },
						0);
		model.addAttribute("terminals", JsonUtils.toJson(terminals));

		if (flag != null) {
			return "/member/edit_info";
		}
		return "/member/edit";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody ResultMsg update(Member member, Long memberRankId,
			Long[] storeId, Long pc_id, Long parentId, Long[] roleId, Long saleOrgId,
			Long[] warehouseId, Boolean isAdministrator, Long[] terminalId,
			HttpServletRequest request, ModelMap model) {
		Member pMember = memberService.find(member.getId());

		if (ConvertUtil.isEmpty(member.getMobile())) {
			// 用户名或手机号未填
			return error("1601002");
		}

		if (member.getPinCode() != null) {
			Member m = memberService.findByPinCode(member.getPinCode());
			if (m != null && m.getId() != member.getId()) {
				return error("操作员PIN码在系统中已存在");
			}
		}

		Setting setting = SettingUtils.get();
		if (StringUtils.isNotEmpty(member.getPassword())) {
			if (member.getPassword().length() < setting.getPasswordMinLength()
					|| member.getPassword().length() > setting.getPasswordMaxLength()) {
				// 密码长度范围有误
				return error("1601005");
			}
		}

		if (StringUtils.isEmpty(member.getPassword())) {
			member.setPassword(pMember.getPassword());
		}
		else {
			member.setPassword(DigestUtils.md5Hex(member.getPassword()));
		}
		Member m = memberService.findByMobile(member.getMobile(),
				member.getCompanyInfoId());
		if (m != null && !m.getId().equals(member.getId())) {
			// 手机号已存在
			return error("1601006");
		}
		else {
			BeanUtils.copyProperties(member,
					pMember,
					new String[] { "id",
							"username",
							"registerIp",
							"loginIp",
							"loginDate",
							"memberOfSaleOrgs",
							"createByAdmin" });
		}

		// 更新用户
		memberService.updateMember(pMember,
				roleId,
				saleOrgId,
				isAdministrator,
				terminalId);

		return success();
	}

	/**
	 * 点击用户头像弹出更新
	 */
	@RequestMapping(value = "/update_info", method = RequestMethod.POST)
	public @ResponseBody ResultMsg update_info(Member member) {

		Setting setting = SettingUtils.get();
		if (StringUtils.isNotEmpty(member.getPassword())) {
			if (member.getPassword().length() < setting.getPasswordMinLength()
					|| member.getPassword().length() > setting.getPasswordMaxLength()) {
				// 密码长度范围有误
				return error("1601005");
			}
		}
		memberService.updateInfo(member);

		return success();
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody ResultMsg delete(Long id, ModelMap model) {

		Member member = memberService.find(id);
		memberService.deleteMember(member);
		return success();
	}

}
